package com.snailhd.framework.util.base;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.util.List;

/**
 * json 简单处理类
 * 基于jackson
 */
public class JsonUtils {

    private static final ObjectMapper MAPPER = new ObjectMapper();


    public static String toJSONString(Object obj){
        try {
            return MAPPER.writeValueAsString(obj);
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }
    }

    public static byte[] toJSONBytes(Object obj){
        try {
            return MAPPER.writeValueAsBytes(obj);
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }
    }

    public static <T> T parseObject(String data,Class<T> clazz){
        try {
            return MAPPER.readValue(data,clazz);
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }
    }

    public static <T> List<T> parseArray(String jsonArray,Class<T> clazz){
        JavaType javaType = MAPPER.getTypeFactory().constructParametricType(List.class,clazz);
        try {
            return MAPPER.readValue(jsonArray, javaType);
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }
    }

    public static <T> T parseObject(String text, TypeReference<T> type){
        try {
            return MAPPER.readValue(text,type);
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }
    }
}
